package com.campus.help.controller;

import com.campus.help.common.Result;
import com.campus.help.dto.MerchantLoginDTO;
import com.campus.help.entity.Labor;
import com.campus.help.entity.Merchant;
import com.campus.help.service.MerchantService;
import com.campus.help.utils.JwtUtils;
import com.campus.help.utils.FileStorageUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 商户控制器
 */
@Slf4j
@RestController
@RequestMapping("/merchant")
public class MerchantController {

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private JwtUtils jwtUtils;
    
    @Autowired
    private FileStorageUtils fileStorageUtils;

    @Autowired
    private com.campus.help.service.WeChatSecurityService weChatSecurityService;

    /**
     * 商户登录
     */
    @PostMapping("/login")
    public Result login(@RequestBody MerchantLoginDTO loginDTO) {
        log.info("商户登录: {}", loginDTO.getUsername());

        try {
            return merchantService.login(loginDTO);
        } catch (Exception e) {
            log.error("商户登录异常", e);
            return Result.error("登录失败，请稍后重试");
        }
    }

    /**
     * 获取当前商户信息
     */
    @GetMapping("/info")
    public Result getMerchantInfo(HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return Result.error(401, "未登录或token无效");
            }

            // 验证token并获取商户信息
            JwtUtils.TokenInfo tokenInfo = jwtUtils.validateToken(token);
            if (tokenInfo == null || tokenInfo.getMerchantId() == null) {
                return Result.error(401, "token已过期或无效");
            }

            // 根据token中的商户ID获取商户信息
            Long merchantId = tokenInfo.getMerchantId();
            Merchant merchant = merchantService.getById(merchantId);

            if (merchant == null) {
                return Result.error(404, "商户不存在");
            }

            // 返回商户信息（脱敏）
            return Result.success(buildMerchantInfo(merchant));

        } catch (Exception e) {
            log.error("获取商户信息异常", e);
            return Result.error("获取信息失败");
        }
    }

    /**
     * 商户退出登录
     */
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            log.info("商户退出登录, token: {}", token != null ? "有效" : "无效");

            // 这里可以将token加入黑名单，暂时简单返回成功
            return Result.success("退出登录成功");

        } catch (Exception e) {
            log.error("商户退出登录异常", e);
            return Result.error("退出登录失败");
        }
    }

    /**
     * 修改密码
     */
    @PostMapping("/changePassword")
    public Result changePassword(@RequestBody Map<String, String> params, HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return Result.error(401, "未登录或token无效");
            }

            JwtUtils.TokenInfo tokenInfo = jwtUtils.validateToken(token);
            if (tokenInfo == null || tokenInfo.getMerchantId() == null) {
                return Result.error(401, "token已过期或无效");
            }

            String oldPassword = params.get("oldPassword");
            String newPassword = params.get("newPassword");

            if (oldPassword == null || newPassword == null) {
                return Result.error(400, "旧密码和新密码不能为空");
            }

            Long merchantId = tokenInfo.getMerchantId();
            
            // 调用服务层修改密码
            boolean success = merchantService.changePassword(merchantId, oldPassword, newPassword);
            
            if (success) {
                return Result.success("密码修改成功");
            } else {
                return Result.error("旧密码错误");
            }

        } catch (Exception e) {
            log.error("修改密码异常", e);
            return Result.error("修改密码失败");
        }
    }

    /**
     * 获取商户统计信息
     */
    @GetMapping("/stats")
    public Result getStats(HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return Result.error(401, "未登录或token无效");
            }

            JwtUtils.TokenInfo tokenInfo = jwtUtils.validateToken(token);
            if (tokenInfo == null || tokenInfo.getMerchantId() == null) {
                return Result.error(401, "token已过期或无效");
            }

            Long merchantId = tokenInfo.getMerchantId();
            
            // 调用服务层获取统计信息
            Map<String, Object> stats = merchantService.getMerchantStats(merchantId);

            return Result.success(stats);

        } catch (Exception e) {
            log.error("获取商户统计信息异常", e);
            return Result.error("获取统计信息失败");
        }
    }

    /**
     * 商户发布劳务
     */
    @PostMapping("/labors")
    public Result publishLabor(@RequestBody com.campus.help.entity.Labor labor, HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return Result.error(401, "未登录或token无效");
            }

            JwtUtils.TokenInfo tokenInfo = jwtUtils.validateToken(token);
            if (tokenInfo == null || tokenInfo.getMerchantId() == null) {
                return Result.error(401, "token已过期或无效");
            }

            Long merchantId = tokenInfo.getMerchantId();
            
            log.info("商户发布劳务: merchantId={}, jobTitle={}, typeId={}", 
                merchantId, labor.getJobTitle(), labor.getTypeId());

            // 内容安全检测
            boolean isSafe = weChatSecurityService.checkLaborContentSecurity(
                    labor.getJobTitle(), 
                    labor.getDescription()
            );
            
            if (!isSafe) {
                log.warn("商户发布内容包含违规信息: merchantId={}, jobTitle={}", merchantId, labor.getJobTitle());
                return Result.error("发布失败：您发布的内容包含违规信息，请修改后重新发布");
            }

            // 调用服务层发布劳务
            Labor publishedLabor = merchantService.publishLabor(labor, merchantId);

            return Result.success("发布成功", publishedLabor);

        } catch (Exception e) {
            log.error("商户发布劳务异常", e);
            return Result.error("发布劳务失败: " + e.getMessage());
        }
    }

    /**
     * 更新劳务信息
     */
    @PutMapping("/labors/{id}")
    public Result updateLabor(
            @PathVariable Long id,
            @RequestBody Labor labor,
            HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return Result.error(401, "未登录或token无效");
            }

            JwtUtils.TokenInfo tokenInfo = jwtUtils.validateToken(token);
            if (tokenInfo == null || tokenInfo.getMerchantId() == null) {
                return Result.error(401, "token已过期或无效");
            }

            Long merchantId = tokenInfo.getMerchantId();
            labor.setId(id);
            
            log.info("商户更新劳务: merchantId={}, laborId={}", merchantId, id);

            // 调用服务层更新劳务
            Labor updatedLabor = merchantService.updateLabor(labor, merchantId);

            return Result.success("更新成功", updatedLabor);

        } catch (Exception e) {
            log.error("商户更新劳务异常", e);
            return Result.error("更新劳务失败: " + e.getMessage());
        }
    }

    /**
     * 关闭/删除劳务
     */
    @DeleteMapping("/labors/{id}")
    public Result deleteLabor(@PathVariable Long id, HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return Result.error(401, "未登录或token无效");
            }

            JwtUtils.TokenInfo tokenInfo = jwtUtils.validateToken(token);
            if (tokenInfo == null || tokenInfo.getMerchantId() == null) {
                return Result.error(401, "token已过期或无效");
            }

            Long merchantId = tokenInfo.getMerchantId();
            
            log.info("商户关闭劳务: merchantId={}, laborId={}", merchantId, id);

            // 调用服务层关闭劳务
            boolean success = merchantService.closeLabor(id, merchantId);

            if (success) {
                return Result.success("关闭成功");
            } else {
                return Result.error("关闭失败");
            }

        } catch (Exception e) {
            log.error("商户关闭劳务异常", e);
            return Result.error("关闭劳务失败: " + e.getMessage());
        }
    }

    /**
     * 获取劳务详情
     */
    @GetMapping("/labors/{id}")
    public Result getLaborDetail(@PathVariable Long id, HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return Result.error(401, "未登录或token无效");
            }

            JwtUtils.TokenInfo tokenInfo = jwtUtils.validateToken(token);
            if (tokenInfo == null || tokenInfo.getMerchantId() == null) {
                return Result.error(401, "token已过期或无效");
            }

            Long merchantId = tokenInfo.getMerchantId();
            
            // 获取劳务详情
            Labor labor = merchantService.getLaborDetail(id, merchantId);

            if (labor == null) {
                return Result.error(404, "劳务不存在或无权访问");
            }

            return Result.success(labor);

        } catch (Exception e) {
            log.error("获取劳务详情异常", e);
            return Result.error("获取劳务详情失败: " + e.getMessage());
        }
    }

    /**
     * 获取商户发布的劳务列表
     */
    @GetMapping("/labors")
    public Result getMerchantLabors(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String jobTitle,
            @RequestParam(required = false) Long typeId,
            @RequestParam(required = false) String workType,
            @RequestParam(required = false) String status,
            HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return Result.error(401, "未登录或token无效");
            }

            JwtUtils.TokenInfo tokenInfo = jwtUtils.validateToken(token);
            if (tokenInfo == null || tokenInfo.getMerchantId() == null) {
                return Result.error(401, "token已过期或无效");
            }

            Long merchantId = tokenInfo.getMerchantId();
            
            // 获取分页数据，传递搜索参数
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.campus.help.vo.MerchantLaborVO> laborPage = 
                merchantService.getMerchantLabors(merchantId, page, size, jobTitle, typeId, workType, status);

            // 构建返回数据
            Map<String, Object> result = new HashMap<>();
            result.put("list", laborPage.getRecords());
            result.put("total", laborPage.getTotal());
            result.put("page", laborPage.getCurrent());
            result.put("size", laborPage.getSize());
            result.put("pages", laborPage.getPages());

            return Result.success(result);

        } catch (Exception e) {
            log.error("获取商户劳务列表异常", e);
            return Result.error("获取劳务列表失败");
        }
    }

    /**
     * 获取劳务的申请列表
     */
    @GetMapping("/labors/{laborId}/applications")
    public Result getLaborApplications(
            @PathVariable Long laborId,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return Result.error(401, "未登录或token无效");
            }

            JwtUtils.TokenInfo tokenInfo = jwtUtils.validateToken(token);
            if (tokenInfo == null || tokenInfo.getMerchantId() == null) {
                return Result.error(401, "token已过期或无效");
            }

            Long merchantId = tokenInfo.getMerchantId();
            
            // 获取劳务申请列表
            com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.campus.help.vo.LaborApplicationVO> applicationPage = 
                merchantService.getLaborApplications(laborId, merchantId, page, size);

            // 构建返回数据
            Map<String, Object> result = new HashMap<>();
            result.put("list", applicationPage.getRecords());
            result.put("total", applicationPage.getTotal());
            result.put("page", applicationPage.getCurrent());
            result.put("size", applicationPage.getSize());
            result.put("pages", applicationPage.getPages());

            return Result.success(result);

        } catch (Exception e) {
            log.error("获取劳务申请列表异常", e);
            return Result.error("获取申请列表失败: " + e.getMessage());
        }
    }

    /**
     * 审核劳务申请
     */
    @PostMapping("/applications/{applicationId}/review")
    public Result reviewApplication(
            @PathVariable Long applicationId,
            @RequestBody Map<String, Object> params,
            HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return Result.error(401, "未登录或token无效");
            }

            JwtUtils.TokenInfo tokenInfo = jwtUtils.validateToken(token);
            if (tokenInfo == null || tokenInfo.getMerchantId() == null) {
                return Result.error(401, "token已过期或无效");
            }

            Long merchantId = tokenInfo.getMerchantId();
            String status = (String) params.get("status");
            String reviewNote = (String) params.get("reviewNote");
            
            if (status == null || (!"approved".equals(status) && !"rejected".equals(status))) {
                return Result.error(400, "审核状态无效");
            }
            
            log.info("商户审核申请: merchantId={}, applicationId={}, status={}", 
                merchantId, applicationId, status);

            // 调用服务层审核申请
            boolean success = merchantService.reviewApplication(
                applicationId, merchantId, status, reviewNote);

            if (success) {
                return Result.success("审核成功");
            } else {
                return Result.error("审核失败");
            }

        } catch (Exception e) {
            log.error("审核申请异常", e);
            return Result.error("审核失败: " + e.getMessage());
        }
    }

    /**
     * 更新商户信息
     */
    @PutMapping("/info")
    public Result updateMerchantInfo(
            @RequestBody Merchant merchant,
            HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            if (token == null) {
                return Result.error(401, "未登录或token无效");
            }

            JwtUtils.TokenInfo tokenInfo = jwtUtils.validateToken(token);
            if (tokenInfo == null || tokenInfo.getMerchantId() == null) {
                return Result.error(401, "token已过期或无效");
            }

            Long merchantId = tokenInfo.getMerchantId();
            merchant.setId(merchantId);
            
            log.info("商户更新信息: merchantId={}", merchantId);

            // 调用服务层更新商户信息
            Merchant updatedMerchant = merchantService.updateMerchantInfo(merchant);

            return Result.success("更新成功", buildMerchantInfo(updatedMerchant));

        } catch (Exception e) {
            log.error("更新商户信息异常", e);
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 从请求中获取token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }
        return null;
    }

    /**
     * 构建商户信息（脱敏）
     */
    private Map<String, Object> buildMerchantInfo(Merchant merchant) {
        Map<String, Object> merchantInfo = new HashMap<>();
        merchantInfo.put("id", merchant.getId());
        merchantInfo.put("username", merchant.getUsername());
        merchantInfo.put("merchantName", merchant.getMerchantName() != null ? merchant.getMerchantName() : "");
        merchantInfo.put("contactPerson", merchant.getContactPerson() != null ? merchant.getContactPerson() : "");
        merchantInfo.put("phone", merchant.getPhone() != null ? merchant.getPhone() : "");
        merchantInfo.put("email", merchant.getEmail() != null ? merchant.getEmail() : "");
        merchantInfo.put("address", merchant.getAddress() != null ? merchant.getAddress() : "");
        merchantInfo.put("avatar", merchant.getAvatar() != null ? merchant.getAvatar() : "");
        merchantInfo.put("description", merchant.getDescription() != null ? merchant.getDescription() : "");
        merchantInfo.put("status", merchant.getStatus());
        merchantInfo.put("lastLoginTime", merchant.getLastLoginTime());
        merchantInfo.put("loginCount", merchant.getLoginCount());
        merchantInfo.put("userType", "merchant");
        return merchantInfo;
    }
    
    /**
     * 商户上传文件（带权限验证）
     */
    @PostMapping("/upload")
    public Result uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        try {
            // Token 验证
            String token = getTokenFromRequest(request);
            if (token == null) {
                return Result.error(401, "未登录或token无效");
            }

            JwtUtils.TokenInfo tokenInfo = jwtUtils.validateToken(token);
            if (tokenInfo == null || tokenInfo.getMerchantId() == null) {
                return Result.error(401, "token已过期或无效");
            }

            Long merchantId = tokenInfo.getMerchantId();
            
            // 文件验证
            if (file.isEmpty()) {
                return Result.error("文件不能为空");
            }

            // 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return Result.error("只支持图片文件");
            }
            
            // 检查文件大小（限制2MB）
            long maxSize = 2 * 1024 * 1024; // 2MB
            if (file.getSize() > maxSize) {
                return Result.error("图片大小不能超过2MB");
            }

            // 上传文件
            String fileName = fileStorageUtils.uploadFile(file, "merchant/" + merchantId);
            String fileUrl = fileStorageUtils.getFileUrl(fileName);

            Map<String, Object> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("key", fileName);

            log.info("商户上传文件成功: merchantId={}, fileName={}", merchantId, fileName);
            return Result.success(result);
            
        } catch (Exception e) {
            log.error("商户上传文件失败", e);
            return Result.error("文件上传失败: " + e.getMessage());
        }
    }
}